<template>
  <div class="tracetask-container">
    <v-layout wrap justify-center align-center>
      <v-flex md12>
        <v-layout wrap justify-space-between>
          <v-flex md4 d-flex align-center>
            <v-text-field
            v-model="queryForm.beginPrice"
            label="Low Price"
            ></v-text-field>
            <span> - </span>
            <v-text-field
              v-model="queryForm.endPrice"
              label="High Price"
            ></v-text-field>
            <v-btn round color="primary" @click="onSearch">Go</v-btn>
          </v-flex>
          <v-flex md3>
            <v-select
              label="Category"
              :items="categories"
              v-model="queryForm.category"
            ></v-select>
          </v-flex>
          <v-flex md2>
            <v-select
              :items="sorts"
              v-model="queryForm.sortWay"
            ></v-select>
          </v-flex>
          <v-flex md2>
            <v-btn color="primary" round @click="onResetAll">
              <span>Reset All</span>
            </v-btn>
          </v-flex>
        </v-layout>
      </v-flex>
      <v-flex md12 mt-4>
        <!-- <h2 style="text-align: left;">{{ $category.name }}</h2> -->
        <v-layout class="list" justify-start align-start wrap>
          <v-flex
            px-2
            class="card item cursor"
            v-for="(item, i) of missionList"
            @click="onMissionDetail(item)"
          >
            <ui-mission :mission="item" />
          </v-flex>

      <v-flex md12 v-if="showNoData">
        Nothing to show.
      </v-flex>
        </v-layout>
      </v-flex>

      <v-flex md12 v-if="missionList.length > 0">
        <v-pagination
          @change="onPageChange"
          :length="pagination.pageCount"
          circle
          total-visible="5"
          v-model="pagination.page"
        ></v-pagination>
      </v-flex>
    </v-layout>
  </div>
</template>


<script lang="ts">
// 使用类装饰器
import { Component, Vue } from "vue-property-decorator";
import { Api } from "@/api";
import { forEach } from "lodash";
import { KV } from "@/utils/type";
import { PageOptions, TopupStatusKV } from "@/utils/constants";
import { ReqProfitIncome, ReqTaskInfo } from "@/api/bean";
import { getTime } from "@/utils/commonUtils";
import Cookie from 'js-cookie';
import { State, Action, Mutation, Getter, namespace } from "vuex-class";
const varsModule = namespace('varsModule');
const userModule = namespace('userModule');
declare const $Vue: Vue;

@Component
export default class Missions extends Vue {

  @varsModule.State('$category') $category: any;
  @userModule.Action('logoutFN') logoutFN: any;

  private carouselItems: any = [{
    imageUrl: require('@/assets/images/c1.png'),
  }]

  private categories: Array<KV> = [
    { text: "", value: '' },
    { text: "Prime Video", value: 1 },
    { text: "Music, CDs & Vinyl", value: 2 },
    { text: "Digital Music", value: 3 },
    { text: "Kindle Store", value: 4 },
    { text: "Arts & Crafts", value: 5 },
    { text: "Automotive", value: 6 },
    { text: "Baby", value: 7 },
    { text: "Beauty & Personal Care", value: 8 },
    { text: "Books", value: 9 },
    { text: "Computers", value: 10 },
    { text: "Electronics", value: 11 },
    { text: "Women's Fashion", value: 12 },
    { text: "Men's Fashion", value: 13 },
    { text: "Girls' Fashion", value: 14 },
    { text: "Boys' Fashion", value: 15 },
    { text: "Health & Household", value: 16 },
    { text: "Home & Kitchen", value: 17 },
    { text: "Industrial & Scientific", value: 18 },
    { text: "Luggage", value: 19 },
    { text: "Movies & Television", value: 20 },
    { text: "Pet Supplies", value: 21 },
    { text: "Software", value: 22 },
    { text: "Sports & Outdoors", value: 23 },
    { text: "Tools & Home Improvement", value: 24 },
    { text: "Toys & Games", value: 25 },
    { text: "Video Games", value: 26 }
  ];

  private websites: Array<KV> = [
    { text: "", value: '' },
    { text: "USA", value: 1 },
    { text: "France", value: 2 }
  ];

  private sorts: Array<KV> = [
    { text: "Default rank", value: 0 },
    { text: "Price: Low to High", value: 2 },
    { text: "Price: High to Low", value: 1 },
    { text: "Newest", value: 0 }
  ];

  private pageOptions: any = [];
  private buyerStatus: any = TopupStatusKV;

  private queryForm: any = {
    beginPrice: "",
    endPrice: '',
    category: '',
    sortWay: '',
  };

  private headers: Array<any> = [];

  private missionList: any = [
  ];

  private loading: boolean = false;
  private dialog: boolean = false;
  private dialogItem: any = {};
  private isQuery: boolean = false;
  
  private showNoData: boolean = false;

  private pagination: any = {
    pageCount: 1,
    page: 1,
    limit: 25,
    offset: 0
  };

  private getTime(date: string) {
    return getTime(date);
  }

  protected mounted() {

    this.getMissionList();
    if (!Cookie.get('p_token')) {
      this.logoutFN();
    }
    // $Vue.$emit("balance");

    // $Vue.$emit("title", { message: 'Missions' });
    this.pageOptions = PageOptions.slice();
    $Vue.$once('refresh', ()=>{
      this.getMissionList();
    });
    $Vue.$off('Missions');
    $Vue.$on('Missions', ()=>{
      this.getMissionList();
    });

  }

  private onResetAll() {
    this.queryForm = {
      category: '',
      beginPrice: '',
      endPrice: '',
      sortWay: '',
    };
  }

  private onPageOptionChange(value: any) {
    this.pagination.page = 1;
    this.pagination.offset = 0;
  }

  private onSearch(from?: string) {
    let params: any = {};

    let valid = 0;
    forEach(this.queryForm, (item, key) => {
      item ? (params[key] = item) : valid++;
    });

    if (from === undefined) {
      this.pagination.offset = 0;
      this.pagination.page = 1;
    }

    params.limit = this.pagination.limit;
    params.offset = this.pagination.offset;
    this.isQuery = true;
    this.getMissionList(params);
  }

  private onJoinMissionClicked(item: any) {
    this.joinMission(item);
  }

  private onMissionDetail(data: any) {
    sessionStorage.setItem("MissionDetail", JSON.stringify(data));
    this.$router.push({
      name: "MissionDetail",
      params: data
    });
  }

  private onPageChange(value: any) {
    let limit = this.pagination.limit;
    this.pagination.offset = (value - 1) * limit;
    if (!this.isQuery) {
      this.getMissionList();
    } else {
      this.onSearch("wyvonj");
    }
  }

  private async getMissionList(queryForm?: any) {
    if (!queryForm) {
      queryForm = {};
    }
    const params: ReqTaskInfo = {
      offset: this.pagination.offset,
      limit: this.pagination.limit,
      ...queryForm,
      publishStatus: 1,
    };
    if (this.$category.value !== -1) {
      params.category = this.$category.value;
    }
    const { data } = await Api.getTaskList.r(params);
    console.log("getTaskList", data);
    if (data.result === 0) {
      let $data = data.data;
      // 设置总数
      // this.pagination.pageCount = data.data.totalCount;
      // this.pagination.offset += data.data.dataList.length;
      let userId: any = Cookie.get('p_userId');
      $data.dataList.forEach((item: any) => {
        if (item.buyerUserIds !== null) {
          let userIds: Array<string> = item.buyerUserIds.split(",");
          if (userIds.indexOf(userId) === -1) {
            item.showButton = true;
          }
        } else {
          item.showButton = true;
        }
      });

      this.missionList = $data.dataList;
      this.pagination.pageCount = $data.totalCount
        ? Math.ceil($data.totalCount / this.pagination.limit)
        : 1;
      this.showNoData = false;
    } else{
      this.showNoData = true;
    }
  }

  /**
   * 任务抢单 抢单之后可以通过上传 订单和评价截图 用于完成任务
   */
  private async joinMission(task: any) {
    const params = {
      taskId: task.taskId
    };
    const { data } = await Api.competeOrder.r(params);
    console.log("getTaskList", data);
    if (data.result === 0) {
      task.scalped = true;
      $Vue.$emit("snackbar", {
        text: data.message,
      });
    } else {
      alert(data.message);
    }
  }

}
</script>

<style lang="less" scoped>
.tracetask-container {
  width: 100%;
  height: 100%;
}
.pagination-wrapper {
  background: white;
  border-top: 1px solid #d4d4d4;
}
.list {
  padding-top: 0.3rem;
  width: 100%;
  height: 100%;
  padding: 0;
  list-style-type: none;
  text-align: center;
  position: relative;
  .item {
    background-color: white;
    margin-bottom: 0.4rem;
    width: 100%;
    display: flex;
    padding: 6px 0;
    text-align: left;
    justify-content: space-between;
    box-sizing: border-box;
    height: 20rem;
    border-radius: 12px;
    width: 19%;
    max-width: 19%;
    flex-basis: 19%;
    margin-right: 1%;
  }
}
</style>


